####################################
# Appendix G — Continuity figure (2018)
####################################

rm(list=ls())

suppressPackageStartupMessages({
  library(ggplot2)
  library(rdrobust)
  library(lfe)
  library(broom)
})

# --- Directories ---
base_dir <- "~/Dropbox/Issue voting Chile"
fig_dir  <- file.path(base_dir, "09_replication/output")
dir.create(fig_dir, showWarnings = FALSE, recursive = TRUE)

# --- Data (provides d18) ---
load(file.path(base_dir, "09_replication/data/rdd_2025aug19.RData"))

# ---- helper: safe numeric coercion ----
to_num <- function(x) {
  if (is.numeric(x)) return(x)
  if (is.logical(x)) return(as.numeric(x))
  if (is.factor(x))  return(suppressWarnings(as.numeric(as.character(x))))
  suppressWarnings(as.numeric(x))
}

################################
# Continuity 
################################

################################
# Continuity plot
################################

bw_edu = rdbwselect(d18$education_num,d18$margin)$bws[1]
kweights_edu = kernelwts(d18$margin, 0, bw = bw_edu, kernel = "triangular")
m_edu = felm(education_num_s  ~ treatment + margin + treatment*margin | cep + comuna | 0 | comuna, data = d18, weights = kweights_edu, keepCX = TRUE)
r_edu = tidy(m_edu, conf.int = T, conf.level = 0.95)

bw_female = rdbwselect(d18$female,d18$margin)$bws[1]
kweights_female = kernelwts(d18$margin, 0, bw = bw_female, kernel = "triangular")
m_female = felm(female_s  ~ treatment + margin + treatment*margin | cep + comuna | 0 | comuna, data = d18, weights = kweights_female, keepCX = TRUE)
r_female = tidy(m_female, conf.int = T, conf.level = 0.95)

pe = c(r_edu$estimate[1],r_female$estimate[1])
se = c(r_edu$std.error[1],r_female$std.error[1])
upper95 = c(r_edu$conf.high[1],r_female$conf.high[1])
lower95 = c(r_edu$conf.low[1],r_female$conf.low[1])

variable = c("Education","Gender")
variable = as.factor(variable)
results = data.frame(variable,pe,se,lower95,upper95)
results

ggplot(results, aes(x=variable, y=pe)) + 
  geom_pointrange(aes(ymin=lower95,ymax=upper95)) + 
  scale_y_continuous(breaks=c(-2,-1,0,1,2)) + 
  coord_cartesian(ylim=c(-2,2)) + 
  scale_x_discrete(breaks=c("Education","Gender")) + 
  geom_hline(yintercept=0) + 
  xlab("Covariates") + 
  ylab("RDD estimates") + 
  ggtitle("") + 
  theme_bw() + 
  theme(plot.title = element_text(hjust=0.5)) +  
  theme(legend.position="none") +
  theme(text = element_text(size = 20))
ggsave(file="~/Dropbox/Issue voting Chile/09_replication/output/G_rdd_continuity.png",width=10,height=7)




